package com.hfzy.ihk.common.support.againtask;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by YANFA on 2018/7/27.
 */
public class DelayQueueManager {
    private static int thread_num = 5;
    // 线程池，外部传入
    private ExecutorService executor;
    // 守护线程
    private Thread daemonThread;
    // 延时队列

    private static final AtomicLong atomic = new AtomicLong(0);
    private static DelayQueueManager instance = new DelayQueueManager();

    private DelayQueueManager() {
        executor = Executors.newFixedThreadPool(thread_num);
        init();
    }

    public static DelayQueueManager getInstance() {
        return instance;
    }

    /**
     * 初始化
     */
    public void init() {
        daemonThread = new Thread(() -> {
            execute();
        });
        daemonThread.setName("DelayQueueMonitor");
        daemonThread.start();
    }

    private void execute() {
        while (true) {
            Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
            int taskNum = InitDelayQueue.delayQueue.size();
            try {
                // 从延时队列中获取任务
                DelayTask<?> delayTask = InitDelayQueue.delayQueue.take();
                if (delayTask != null) {
                    Runnable task = delayTask.getTask();
                    if (null == task) {
                        continue;
                    }
                    // 提交到线程池执行task
                    executor.execute(task);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加任务
     *
     * @param task
     */
    public void put(DelayWorker task) {
        // 获取延时时间
      //  long timeout = TimeUnit.NANOSECONDS.convert(time, unit);
        // 将任务封装成实现Delayed接口的消息体
        DelayTask<?> delayTask = new DelayTask<DelayWorker>(task);
        // 将消息体放到延时队列中
        InitDelayQueue.delayQueue.put(delayTask);
    }

    /**
     * 删除任务
     *
     * @param task
     * @return
     */
    public boolean removeTask(DelayTask task) {
        return InitDelayQueue.delayQueue.remove(task);
    }

}
